package designpattern.adapter;

import java.util.*;

/**
 * 当希望修改接口，当并不能覆盖原有接口时
 */
class ReversibleArrayList<T> extends ArrayList<T>{

    Collection<T> words;

    public ReversibleArrayList(Collection<T> c){
        super(c);
        words=c;
    }


    /**
     * 倒序遍历
     * @return
     */
    public Iterable<T> reversed(){
        return new Iterable<T>() {
            @Override
            public Iterator<T> iterator() {
                return new Iterator<T>() {
                    int current=size()-1;
                    @Override
                    public boolean hasNext() {
                        return current > -1;
                    }

                    @Override
                    public T next() {
                        return get(current--);
                    }
                };
            }
        };
    }

    /**
     * 随机遍历
     * @return
     */
    public Iterable<T> randomized(){
        return new Iterable<T>() {
            @Override
            public Iterator<T> iterator() {
                //这儿必须得创建副本，否则会打乱原有List顺序
                List<T> shuffled=new ArrayList<>(words);
                Collections.shuffle(shuffled,new Random(47));
                return shuffled.iterator();
            }
        };
    }

}

public class AdapterMethodIdiom {
    public static void main(String[] args) {
        ReversibleArrayList<String> ral=new ReversibleArrayList<>(Arrays.asList("To be or not to be".split(" ")));

        for(String s:ral.randomized()){
            System.out.print(s+" ");
        }

        System.out.println();

        for (String s:ral){
            System.out.print(s+" ");
        }

        System.out.println();

        for(String s:ral.reversed()){
            System.out.print(s+" ");
        }
    }
}
